//
//  XJLocaltionViewController.m
//  XinJiangMall
//
//  Created by Tzyang on 2018/4/10.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJLocaltionViewController.h"
#import "XJSelectCityViewController.h" //选择城市

//View
#import "XJLocationView.h"
#import "XJDimSearchView.h"
#import "XJLocationSearchView.h"

//百度:定位+附近地址
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h>
#import <BaiduMapAPI_Search/BMKPoiSearchType.h>

//百度:模糊搜索
#import <BaiduMapAPI_Search/BMKSuggestionSearch.h>
#import <BaiduMapAPI_Search/BMKPoiSearch.h> //

@interface XJLocaltionViewController ()<UISearchBarDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate, XJLocationSearchViewDelegate>

@property(nonatomic, strong) XJLocationSearchView *locationSearchView;

@property(nonatomic,strong)BMKLocationService* locService;
@property(nonatomic,strong)BMKGeoCodeSearch* geocodesearch;
@property(nonatomic,assign)CLLocationCoordinate2D currentCoordinate;

@property(nonatomic, strong)BMKPoiSearch *poiSearch;

//附近的地址
@property(nonatomic, strong) XJLocationView *locationView;
@property(nonatomic, strong) NSMutableArray *dataSource;

// 模糊搜索
@property(nonatomic, strong)XJDimSearchView *dimSearchView;
@property(nonatomic, strong)NSMutableArray *searchArray; //模糊搜索数据源
@end

@implementation XJLocaltionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupView];
    
    
    // 设置的代理
    self.locService.delegate = self;
    self.geocodesearch.delegate = self;
    self.poiSearch.delegate = self; // 模糊搜索的代理
    
    [self startLocation]; // 开启定位
}


- (void)setupView {
    CGFloat y = kIs_iPhoneX ? ADAPTHeight(44) : ADAPTHeight(20);
    CGFloat searchView_h = ADAPTHeight(50);
    self.locationSearchView = [[XJLocationSearchView alloc] initWithFrame:CGRectMake(0, y, KWidth, searchView_h)];
    [self.view addSubview:self.locationSearchView];
    self.locationSearchView.delegate = self;
    
    
    [self.view addSubview:self.locationView];
    //重新布局frame
    CGFloat locationView_y = self.locationSearchView.rb_bottom;
    self.locationView.frame = CGRectMake(0, locationView_y, KWidth, KHeight - locationView_y);

    [self.view addSubview:self.dimSearchView]; //模糊搜索view.
    self.dimSearchView.frame = CGRectMake(0, locationView_y, KWidth, KHeight - locationView_y);
    self.dimSearchView.hidden = YES;//默认隐藏。点击搜索的时候时显示
}

- (void)localBtnAction:(UIButton *)button {
    XJLog(@"定位城市");
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
}

- (void)cancelBtnClick{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    //一进来就隐藏导航条
    [self.navigationController setNavigationBarHidden:YES animated:YES];
   // self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - XJLocationSearchViewDelegate
- (void)locationSearchViewDelegateClickLeftButtonAction:(UIButton *)button {
    XJLog(@"左边");
    XJSelectCityViewController *searchCityVC = [[XJSelectCityViewController alloc] init];
    
    searchCityVC.selectedCityBlock = ^(NSString *selectedCity) {
        XJLog(@"%@",selectedCity);
        
        [self.locationSearchView configureSelectLeftCityTitle:selectedCity]; //修改左边按钮文字
        
        [self bmkSerchWithKeyStr:selectedCity]; //调用百度搜索
        
    };
    [self.navigationController pushViewController:searchCityVC animated:YES];
}

- (void)locationSearchViewDelegateClickRightCancelButtonAction:(UIButton *)button {
    XJLog(@"右边");
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)locationSearchViewDelegateSearchBarTextDidChange:(NSString *)searchText {
    XJLog(@"输入内容发生改变:%@",searchText);
    
    NSString *keystr = searchText;
    
    // 输入东西才进行搜索
    if (![NSString isEmptyString:keystr]) {
        
        // 要搜索的内容
        [self bmkSerchWithKeyStr:keystr];
    }
}

#pragma mark - lazy 百度地图定位相关 模糊搜索
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)searchArray {
    if (!_searchArray) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}


- (XJLocationView *)locationView {
    if (!_locationView) {
        _locationView = [[XJLocationView alloc] initWithFrame:CGRectMake(0, XJTopNavH, KWidth, KHeight - XJTopNavH)];
        
        XJWeakSelf(self);
        //返回上一界面
        _locationView.didSelectCellBlock = ^(BMKPoiInfo *poiInfoM) {
            [weakself.navigationController popViewControllerAnimated:YES];
            
            //再次使用block 将 poiInfoM 传出去
            if (weakself.locationViewControllerBlock) {
                weakself.locationViewControllerBlock(poiInfoM);
            }
        };
    }
    return _locationView;
}

/***默认隐藏*/
- (XJDimSearchView *)dimSearchView {
    if (!_dimSearchView) {
        _dimSearchView = [[XJDimSearchView alloc] initWithFrame:CGRectMake(0, XJTopNavH, KWidth, KHeight - XJTopNavH)];
        
        XJWeakSelf(self);
        _dimSearchView.dimSearchViewDidSelectCellBlock = ^(BMKPoiInfo *bmkPoiInfo) {
            XJLog(@"%@",bmkPoiInfo.city);
            
            [weakself.navigationController popViewControllerAnimated:YES];
            
            //再次使用block 将 poiInfoM 传出去
            if (weakself.locationViewControllerBlock) {
                weakself.locationViewControllerBlock(bmkPoiInfo);
            }
        };
    }
    return _dimSearchView;
}

//开始定位
-(void)startLocation
{
    [self.locService startUserLocationService];
}

-(BMKLocationService*)locService
{
    if (_locService==nil)
    {
        _locService = [[BMKLocationService alloc]init];
    }
    return _locService;
}


-(BMKGeoCodeSearch*)geocodesearch
{
    if (_geocodesearch==nil)
    {
        _geocodesearch=[[BMKGeoCodeSearch alloc]init];
    }
    return _geocodesearch;
}

// 百度搜索类
- (BMKPoiSearch *)poiSearch{
    if (!_poiSearch) {
        _poiSearch = [[BMKPoiSearch alloc] init];
    }
    return _poiSearch;
}

#pragma mark - methods
-(void)startGeocodesearchWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    //反地理编码
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = coordinate;
    [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
}

-(void)setCurrentCoordinate:(CLLocationCoordinate2D)currentCoordinate
{
    _currentCoordinate=currentCoordinate;
    [self startGeocodesearchWithCoordinate:currentCoordinate];
}

#pragma mark - BMKGeoCodeSearchDelegate

/**
 *返回反地理编码搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结果
 *@param error 错误号，@see BMKSearchErrorCode
 */

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == BMK_SEARCH_NO_ERROR)
    {
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:result.poiList];
        
        self.locationView.locationArray = self.dataSource; // 传值
        [self.locationView xjLocationViewReloadData];
    }
}

#pragma mark - 百度定位代理方法
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    self.currentCoordinate=userLocation.location.coordinate;
    
    if (self.currentCoordinate.latitude!=0)
    {
        [self.locService stopUserLocationService];
    }
}

#pragma mark - 模糊搜索 BMKSuggestionSearchDelegate

- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult *)poiResult errorCode:(BMKSearchErrorCode)errorCode{
    
    NSLog(@"%@",poiResult.poiInfoList);
    
    self.dimSearchView.searchArray = [poiResult.poiInfoList mutableCopy];
    
    [self.dimSearchView xj_dimSearchViewReloadData];
}


- (void)bmkSerchWithKeyStr:(NSString * )keystr {
    // 要搜索的内容
    BMKCitySearchOption *searchOption = [[BMKCitySearchOption alloc] init];
    searchOption.keyword = keystr;
    [self.poiSearch poiSearchInCity:searchOption];
    
    self.dimSearchView.hidden = NO;
}
@end
